package io.wongxd.demo.page

import android.app.Activity
import android.net.Uri
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import coil.compose.AsyncImage
import io.wongxd.demo.AppBtn
import io.wongxd.demo.R
import io.wongxd.demo.V
import io.wongxd.solution.baseView.BaseComposeToolBarFgt
import io.wongxd.solution.compose.photo.activity.PhotoClipperActivity
import io.wongxd.solution.compose.photo.activity.PhotoClipperResult
import io.wongxd.solution.compose.photo.activity.PhotoPickResult
import io.wongxd.solution.compose.photo.activity.PhotoPickerActivity
import io.wongxd.solution.compose.photo.activity.getPhotoClipperResult
import io.wongxd.solution.compose.photo.activity.getPhotoPickResult
import io.wongxd.solution.compose.photo.coil.CoilMediaPhotoProviderFactory
import io.wongxd.solution.compose.photo.coil.CoilPhotoProvider
import io.wongxd.solution.compose.photo.ui.PhotoThumbnailWithViewer
import io.wongxd.solution.fs.getUriFromDrawableRes
import io.wongxd.solution.permission.core.PermissionRequired
import io.wongxd.solution.permission.core.rememberPermissionState
import java.lang.String
import kotlin.let


class FgtPhoto : BaseComposeToolBarFgt() {
    override fun lazyInit() {

    }

    private val showType = mutableStateOf(0)

    @Composable
    override fun Render() {
        val albumPer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            rememberPermissionState(permission = android.Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            rememberPermissionState(permission = android.Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        when (showType.value) {
            1 -> PhotoViewerPage()
            2 -> {
                LaunchedEffect(key1 = Unit, block = {
                    albumPer.launchPermissionRequest()
                })
                PermissionRequired(permissionState = albumPer, permissionNotGrantedContent = {

                }, permissionNotAvailableContent = {

                }) {
                    PhotoPickerPage()
                }
            }

            3 -> PhotoClipperPage()
            else -> {
                Column(
                    Modifier
                        .fillMaxSize()
                        .verticalScroll(rememberScrollState()),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    AppBtn(text = "viewer") {
                        showType.value = 1
                    }

                    V(number = 30)

                    AppBtn(text = "picker") {
                        showType.value = 2
                    }

                    V(number = 30)

                    AppBtn(text = "clipper") {
                        showType.value = 3
                    }

                    V(number = 30)
                }
            }
        }
    }

    @Preview(showBackground = true, backgroundColor = 0xffffffff)
    @Composable
    fun RenderPreView() {

    }
}

@Composable
private fun PhotoViewerPage() {
    val ctx = LocalContext.current

    LazyColumn() {
        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        )
                    )
                )
            }
        }

        item {

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            getUriFromDrawableRes(ctx, R.drawable.top_bar_bk),
                            ratio = 1f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "file:///android_asset/test.png".toUri(),
                            ratio = 0.0125f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = listOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        )
                    )
                )
            }
        }
    }

}

@Composable
private fun PhotoPickerPage() {
    val pickResult = remember {
        mutableStateOf<PhotoPickResult?>(null)
    }

    val pickLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == Activity.RESULT_OK) {
            it.data?.getPhotoPickResult()?.let { ret ->
                pickResult.value = ret
            }
        }
    }

    LazyColumn {
        item(key = "pick-photo") {
            val context = LocalContext.current
            AppBtn("Pick Photo") {
                pickLauncher.launch(
                    PhotoPickerActivity.intentOf(
                        context,
                        CoilMediaPhotoProviderFactory::class.java,
                        pickedItems = arrayListOf<Uri>().apply { pickResult.value?.list?.mapTo(this) { it.uri } }
                    )
                )
            }
        }

        val result = pickResult.value
        if (result != null && result.list.isNotEmpty()) {
            item(key = result.list.map { it.id }.joinToString(",")) {
                val images = remember(pickResult) {
                    result.list.map {
                        CoilPhotoProvider(
                            it.uri,
                            ratio = it.ratio()
                        )
                    }.toList()
                }
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 20.dp, vertical = 20.dp)
                ) {
                    Text(text = "原图：${result.isOriginOpen}")

                    PhotoThumbnailWithViewer(
                        images = images
                    )
                }
            }
        }
    }
}

@Composable
private fun PhotoClipperPage() {
    val clipperResult = remember {
        mutableStateOf<PhotoClipperResult?>(null)
    }

    val pickLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == Activity.RESULT_OK) {
            it.data?.getPhotoClipperResult()?.let { ret ->
                clipperResult.value = ret
            }
        }
    }

    LazyColumn {
        item(key = "clipper-photo") {
            val context = LocalContext.current
            AppBtn("Clip Photo") {
                pickLauncher.launch(
                    PhotoClipperActivity.intentOf(
                        context,
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 0f
                        )
                    )
                )
            }
        }

        val result = clipperResult.value
        if (result != null) {
            item(key = result.uri.toString()) {
                AsyncImage(model = result.uri, contentDescription = "")
            }
        }
    }
}